use pinyin::ToPinyin;
use std::collections::HashSet;

pub fn match_text(text: &str, query: &str) -> bool {
    let text_lower = text.to_lowercase();
    let query_lower = query.to_lowercase();

    // 直接匹配原文
    if text_lower.contains(&query_lower) {
        return true;
    }

    // 如果查询包含数字，则只进行原文匹配
    if query.chars().any(|c| c.is_numeric()) {
        return false;
    }

    // 获取文本的拼音并转换为小写
    let text_pinyin: String = text
        .to_pinyin()
        .filter_map(|p| p)
        .map(|p| p.plain().to_lowercase())
        .collect();

    // 获取查询的拼音并转换为小写
    // 判断查询是否为纯英文
    let query_pinyin = if query.chars().all(|c| c.is_ascii_alphabetic()) {
        query.to_lowercase()
    } else {
        query
            .to_pinyin()
            .filter_map(|p| p)
            .map(|p| p.plain().to_lowercase())
            .collect()
    };

    // 匹配拼音
    text_pinyin.contains(&query_pinyin)
}

pub fn search_apps(
    apps: &[crate::models::app::AppItem],
    query: &str,
) -> Vec<crate::models::app::AppItem> {
    if query.is_empty() {
        return apps.to_vec();
    }

    let mut results = Vec::new();
    let mut seen = HashSet::new();

    for app in apps {
        // 避免重复
        if seen.contains(&app.pkgname) {
            continue;
        }

        // 匹配名称、包名和描述
        if match_text(&app.name, query)
            || match_text(&app.pkgname, query)
            || match_text(&app.more, query)
        {
            results.push(app.clone());
            seen.insert(app.pkgname.clone());
        }
    }

    results
}
